<template>
	<view class="form">
		<ad adpid="1206517737" type="banner"></ad>
		<uni-forms :modelValue="formData" :rules="rules" ref="wifiFormRef" label-width="140" label-position="top">
			<uni-forms-item required label="商户名称" name="provider_name">
				<uni-easyinput trim="all" v-model="formData.provider_name" placeholder="请输入商户名称" />
			</uni-forms-item>
			<uni-forms-item required label="WiFi 名称" name="wifi_name">
				<!-- <uni-easyinput trim="all" v-model="formData.wifi_name" placeholder="请输入 WiFi 名称" /> -->
				<uni-easyinput trim="all" suffixIcon="search" v-model="formData.wifi_name" placeholder="请输入 WiFi 名称"
					@iconClick="iconClick"></uni-easyinput>
			</uni-forms-item>
			<uni-forms-item required name="password" label="WiFi 密码">
				<uni-easyinput trim="all" type="text" v-model="formData.password" placeholder="请输入 WiFi 密码" />
			</uni-forms-item>
		</uni-forms>
		<button @click="submitForm" type="primary" :loading="loading">{{buttonText}}</button>

		<!-- 弹窗选择wifi列表 -->
		<uni-popup ref="dataPicker" background-color="#fff" type="bottom">
			<view class="popup-content">
				<view class="pop-title">
					<text>请选择您想创建的 WiFi</text>
				</view>
				<view class="pop-body">
					<view v-for="item in wifiList.data" :key="item.SSID" @click="onnodeclick(item)" class="item">
						{{item.SSID}}
					</view>
				</view>

			</view>
		</uni-popup>
	</view>
</template>

<script>
	import {
		ref,
		reactive,
		computed
	} from 'vue';
	import {
		onLoad
	} from '@dcloudio/uni-app';
	const db = uniCloud.database();
	const wifiTable = db.collection('wifi')
	const usersTable = db.collection('uni-id-users')
	const qrcode = uniCloud.importObject('qrcode')
	export default {
		setup() {
			let wifiId = ""
			// const buttonText = computed(()=>{
			// 	return 
			// })
			const wifiFormRef = ref();
			const dataPicker = ref('');

			const buttonText = ref("创建");
			let loading = ref(false);
			let updatedId = "";
			const formData = reactive({
				wifi_name: "",
				provider_name: "",
				password: ""
			})
			// 存放附近的wifi列表
			const wifiList = reactive({
				data: []
			})


			onLoad(async (option) => {
				if (option.wifi) {
					buttonText.value = "保存"
					const item = JSON.parse(decodeURIComponent(option.wifi));
					const {
						wifi_name,
						provider_name,
						password,
						_id
					} = item
					formData.wifi_name = wifi_name
					formData.provider_name = provider_name
					formData.password = password
					updatedId = _id
				} else {
					buttonText.value = "创建"
				}

			})
			const rules = {
				provider_name: {
					rules: [{
						required: true,
						errorMessage: '请输入商户名称',
					}]
				},
				wifi_name: {
					rules: [{
						required: true,
						errorMessage: '请输入 WiFi 名称',
					}]
				},
				password: {
					rules: [{
						required: true,
						errorMessage: '请输入 WiFi 密码',
					}]
				}
			}

			const submitForm = () => {
				// console.log("submit")
				const curUserInfo = uni.getStorageSync("userInfo")

				wifiFormRef.value.validate((err, formData) => {
					if (!err) {
						loading.value = true
						uni.showLoading({
							mask: true,
							title: `信息${updatedId?"修改":"创建"}中`
						});

						if (!updatedId) {
							const timeParams = {
								created_user: curUserInfo._id,
								created_time: Date.now()
							}
							wifiTable.add({
								...formData,
								...timeParams
							}).then((res) => {
								wifiId = res.result.id
								// console.log("向wifi表加一条数据res", res)
								//先获取小程序码
								getQrcode()

								// 然后先给小程序码赋参数
								// 将小程序码变成图片
								// 上传图片
								// 最后才将图片文件数据写入wifi表
							})
						} else {
							const timeParams = {
								updated_user: curUserInfo._id,
								updated_time: Date.now()
							}
							// console.log("修改")
							wifiTable.where({
								_id: updatedId
							}).update({
								...formData,
								...timeParams
							}).then((res) => {
								uni.showToast({
									title: '修改成功'
								})
								uni.navigateBack({
									delta: 1,
									success: function() {
										uni.$emit('reloadWifiList')
									}
								});
								uni.hideLoading()
							})

						}



					} else {
						return false
					}
				})
			}

			const updateUserWifi = async () => {
				const {
					result
				} = await usersTable.where("'_id'==$cloudEnv_uid").get()
				const wifi = result.data[0].wifi || []
				wifi.push(wifiId)
				// console.log("wifi", wifi)
				usersTable.where('_id==$cloudEnv_uid').update({
					wifi
				}).then(res => {
					// console.log("更新用户的wifi完成", res)
					uni.navigateBack({
						delta: 1,
						success: function() {
							uni.$emit('reloadIndex')
						}
					});
				}).catch((e) => {
					uni.showToast({
						title: '生成小程序码成功，更新用户wifi信息失败',
						icon: "none"
					})
					uni.hideLoading()
				})
			}
			const getQrcode = () => {
				uni.showLoading({
					title: '正在获取小程序码'
				});
				const params = {
					path: `pages/connectWifi/connectWifi?wifi_id=${wifiId}`,
					width: '100%'
				}
				qrcode.getQrcode(params).then((res) => {
					// console.log("获取的小程序码",res)
					wifiTable.where(`_id=='${wifiId}'`).update({
						qrcode_file: res.fileID

					}).then((res2) => {
						// console.log("res更新文件成功了吗", res2)
						// uni.hideLoading();
						uni.showToast({
							title: '小程序码生成成功',
							icon: "none"
						})
						// 更新User关联的wifi数据
						updateUserWifi()

					})
				}).catch((e) => {
					// console.log("调用云对象-getQrcode报错", e)
					uni.showToast({
						title: '小程序码生成失败',
						icon: "none"
					})
					uni.hideLoading();
				})
			}

			const iconClick = () => {
				uni.startWifi({
					success: (res) => {
						// 成功了的话获取当前已连接的wifi，如果没有的话则显示附近的wifi列表
						uni.getConnectedWifi({
							partialInfo: true,
							success(result) {
								formData.wifi_name = result.wifi.SSID || ""
								// console.log("wifi", result)
							},
							fail(err) {
								uni.getSetting({
									success(res) {
										if (!res.authSetting['scope.userLocation']) {
											uni.authorize({
												scope: 'scope.userLocation',
												success() {
													getWifiList()
												},
												fail(err) {
													// console.log("未授权err", err);
												}
											})
										} else {
											getWifiList()
										}
									}
								})


							}
						})
					},
					fail: (error) => {
						// console.log("初始化失败", error)
					}
				})

			}

			const getWifiList = () => {
				uni.getWifiList({
					success(wifis) {
						// console.log(
						// 	"获取wifi成功",
						// 	wifis)
						uni.onGetWifiList(function(res) {
							// console.log("获取wifi列表", res.wifiList);
							const listFilterEmpty = res.wifiList.filter(item => item.SSID)
							// const curSet = new Set(...listFilterEmpty.map(item=>item.SSID))
							const resultList = []
							wifiList.data = listFilterEmpty.reduce((prev, next) => {

								const temp = prev.some((item) =>
									item.SSID === next.SSID
								)
								if (!temp) {
									return prev.concat(next)
								} else {
									return prev
								}
							}, [])
							dataPicker.value.open()
						})
						// wifiList.data =
						// 	wifis
					},
					fail(result) {
						// console.log(
						// 	"获取wifi失败",
						// 	result)
					}
				})
			}

			const onnodeclick = (data) => {
				// console.log("onnodeclick", data)
				formData.wifi_name = data.SSID || ""
				dataPicker.value.close()
			}
			return {
				rules,
				formData,
				submitForm,
				wifiFormRef,
				buttonText,
				loading,
				iconClick,
				onnodeclick,
				dataPicker,
				wifiList
			};
		}
	}
</script>

<style lang="scss">
	.form {
		padding: 15px;
		background-color: #ffffff;
	}

	.pop-title {
		text-align: center;
		font-size: 32rpx;
		line-height: 44px;
	}

	.pop-body {
		overflow-y: auto;
	}

	.item {
		padding: 12px 15px;
	}
</style>
